<?php

namespace AgilePayments\UMFintech;

use AgilePayments\Config;
use AgilePayments\Tool;


class Register
{
    private $mer_id;

    private $pay_config;

    private $base_url;

    public function __construct(Config $config)
    {
        $this->pay_config = $config->pay_type_config;

        $this->mer_id = $this->pay_config->mid;

        $this->base_url = $config->base_url;
    }

    /**
     * @desc 个人子商户注册
     * @param $notify_url   string 回调地址
     * @param $order_id string 订单编号
     * @param $shop_id  string 商户给子商户分配的内部唯一编号
     * @param $mobile_id    string 商户手机号
     * @param $cust_name    string 填写真实姓名
     * @param $identity_code    string 证件号(身份证）
     * @param $sub_mer_alias    string 业务别名，比如店铺名称
     * @return mixed
     */
    public function personal($notify_url, $order_id, $shop_id, $mobile_id, $cust_name, $identity_code, $sub_mer_alias = '')
    {
        $_url = $this->base_url . 'merAccess/register/personal';

        $data = [
            'mer_id'        => $this->mer_id,
            'notify_url'    => $notify_url,
            'version'       => '1.0',
            'order_id'      => $order_id,
            'mer_date'      => date('Ymd'),
            'mer_cust_id'   => $shop_id,
            'user_type'     => '1',
            'mobile_id'     => $mobile_id,
            'cust_name'     => Util::encrypt($cust_name),
            'identity_type' => '1',
            'identity_code' => Util::encrypt($identity_code),
            'sub_mer_alias' => $sub_mer_alias,
        ];
        return json_decode(Util::httpPost($data,$_url),1);
    }

    /**
     * @desc 提交企业子商户基础信息
     * @param String $notify_url
     * @param String $sub_mer_id        商铺编号
     * @param String $order_id          订单编号
     * @param String $sub_mer_name      营业执照上的商户名称
     * @param String $sub_mer_type      3（企业商户）、2（个体工商户）
     * @param String $sub_mer_alias     商户名称的业务别名，比如店铺名称
     * @param String $cert_type         证件类型，1：营业执照 2：统一社会信用代码
     * @param String $legal_name        法人姓名
     * @param String $identity_id       法人证件号
     * @param String $contacts_name     业务联系人姓名
     * @param String $mobile_id         业务联系人姓名
     * @param String $email             业务联系人的邮箱
     * @param String $address           商户的联系地址
     */
    public function submer($notify_url,  $order_id, $sub_mer_name, $cert_id, $sub_mer_type, $sub_mer_alias, $cert_type, $legal_name, $identity_id, $contacts_name, $mobile_id, $email = '', $address = '')
    {
        $_url = $this->base_url . 'merAccess/register/submer';

        $data = [
            'mer_id'        => $this->mer_id,
            'notify_url'    => $notify_url,
            'sub_mer_id'    => $order_id,
            'order_id'      => $order_id,
            'sub_mer_name'  => $sub_mer_name, // 营业执照上名称
            'version'       => '1.0',
            'mer_date'      => date("Ymd"),
            'sub_mer_type'  => $sub_mer_type,
            'sub_mer_alias' => $sub_mer_alias, // 店铺名
            'cert_type'     => $cert_type,
            'cert_id'       => $cert_id,
            'legal_name'	=> Util::encrypt($legal_name),
            'identity_id'	=> Util::encrypt($identity_id),
            'contacts_name'	=> Util::encrypt($contacts_name),
            'mobile_id'	    => $mobile_id,
            'email'	        => $email,
            'address'	    => $address,
        ];

        return json_decode(Util::httpPost($data, $_url),true);
        /*
        var_export($obj->submer('https://test.feiyangyinxiang.cn/api/e_sign/signNotify', '17', $order_id, '沈阳芊韵信息技术有限公司', '91210103MA7C281H9F', '3', 'CCNB官方店铺', '2', '刘旭东', '210624199402270016', '刘旭东', '18842452238'));
//        (object) array( 'meta' => (object) array( 'ret_code' => '0000', 'ret_msg' => '交易成功', ), 'data' => (object) array( 'mer_id' => '51328', 'version' => '1.0', 'reg_date' => '20230625', 'order_id' => 'UMFSR168768253160585', 'mer_date' => '20230625', 'sub_mer_id' => '17', 'user_id' => '00408252', ), 'links' => NULL, )

            file_put_contents('./conSignNotify.txt',json_encode($_SERVER) . PHP_EOL ,FILE_APPEND);
            file_put_contents('./conSignNotify.txt',json_encode($_REQUEST) . PHP_EOL ,FILE_APPEND);
            file_put_contents('./conSignNotify.txt',json_encode($_POST) . PHP_EOL ,FILE_APPEND);
            file_put_contents('./conSignNotify.txt',json_encode($_GET) . PHP_EOL ,FILE_APPEND);
            file_put_contents('./conSignNotify.txt',file_get_contents("php://input") . PHP_EOL ,FILE_APPEND);
            file_put_contents('./conSignNotify.txt','--------------fail---------------' . PHP_EOL ,FILE_APPEND);

{"USER":"www","HOME":"\/home\/www","HTTP_CONTENT_LENGTH":"255","HTTP_HOST":"test.feiyangyinxiang.cn","HTTP_USER_AGENT":"Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/59.0.3071.115 Safari\/537.36","HTTP_SIGNATURE":"cipQm0+Akn2riUjQSvWgwwnfmmVsWW8u1H2tSGp+5YV6zRUqxvIEB5wZOls67vAYzS\/+7sEGBWpNWRePof0s80S2GpjwU4kNi8L95dI\/kulRjL3+N2O4xuRU+ztnZHSejMjzyjHG0594u19Fr5ncTXGSeiqwVrukXg\/HYFqi1uU=","HTTP_CONTENT_TYPE":"application\/json","PATH_INFO":"\/api\/e_sign\/signNotify","REDIRECT_STATUS":"200","SERVER_NAME":"test.feiyangyinxiang.cn","SERVER_PORT":"443","SERVER_ADDR":"172.23.247.118","REMOTE_PORT":"38227","REMOTE_ADDR":"115.182.232.104","SERVER_SOFTWARE":"nginx\/1.21.4","GATEWAY_INTERFACE":"CGI\/1.1","HTTPS":"on","REQUEST_SCHEME":"https","SERVER_PROTOCOL":"HTTP\/1.1","DOCUMENT_ROOT":"\/www\/wwwroot\/test.feiyangyinxiang.cn\/public","DOCUMENT_URI":"\/index.php","REQUEST_URI":"\/api\/e_sign\/signNotify","SCRIPT_NAME":"\/index.php","CONTENT_LENGTH":"255","CONTENT_TYPE":"application\/json","REQUEST_METHOD":"POST","QUERY_STRING":"s=\/api\/e_sign\/signNotify","SCRIPT_FILENAME":"\/www\/wwwroot\/test.feiyangyinxiang.cn\/public\/index.php","FCGI_ROLE":"RESPONDER","PHP_SELF":"\/index.php","REQUEST_TIME_FLOAT":1687683220.101098,"REQUEST_TIME":1687683220}
{"s":"\/api\/e_sign\/signNotify"}
[]
[]
version=4.0&{"meta":{"ret_code":"0000","ret_msg":"交易成功"},"data":{"reg_date":"20230625","acc_type":"208","mer_id":"51328","mer_date":"20230625","user_id":"00408252","version":"1.0","order_id":"UMFSR168768253160585","mer_cust_id":"17"},"links":null}
        */

    }


    /**
     * @desc 提交企业子商户资质文件
     * @param String $notify_url 回调地址
     * @param String $user_id  商户在联动的编号
     * @param String $user_type 用户类型 2：个体商户，3：企业商户
     * @param String $zipPath  资料地址
     * @param String $fileName  压缩包名称
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function materials($notify_url, $user_id, $user_type, $zipPath, $fileName)
    {
        $_url = $this->base_url . '/merAccess/file/upload/materials';

        $zipContens = file_get_contents($zipPath);
        $data = [
            'mer_id'        => $this->mer_id,
            'notify_url'    => $notify_url,
            'version'       => '1.0',
            'user_id'       => $user_id,
            'user_type'     => $user_type, // 2：个体商户，3：企业商户
            'md5_cipher'    => md5($zipContens),
        ];

        ksort($data);

        $jsonData = json_encode($data);

        $sign = Util::sign($jsonData);


        $client = new \GuzzleHttp\Client(['verify' =>false,'timeout'=>3]);
        $post['headers'] = [
            "Signature"=>$sign
        ];
        $optionData = [
            'multipart' => [
                [
                    'name' => 'file',
                    'filename' => $fileName,
                    'contents' => $zipContens
                ]
            ]
        ];
        $post = array_merge($post,$optionData);
        array_push($post['multipart'], ['name' => 'data', 'contents' => $jsonData]);
        Tool::log("HTTP_MATERIALS_START",'info');
        Tool::log("本次请求原始数据 " . PHP_EOL . " URL: ". $_url . PHP_EOL  . " Data: ". $jsonData ,'info');
        $res = $client->request('POST',$_url,$post);
        $body = $res->getBody();
        $head = $res->getHeaders();
        $body_content = $body->getContents();
        $r = json_decode($body_content, 1);
        Tool::log("响应HEAD为： " . json_encode($head),'info');
        Tool::log("响应数据为： " . $body_content,'info');
        Tool::log("HTTP_MATERIALS_END",'info');
        return $r;
    }

    /**
     * @desc 子商户查询接口
     */
    public function memberInfo($shop_id )
    {
        $_url = $this->base_url . 'merAccess/member/memberInfo';
        $data = [
            'mer_id'        => $this->mer_id,
            'version'       => '1.0',
            'sub_mer_id'    => $shop_id,
        ];
        return json_decode(Util::httpGet($data, $_url),1);
    }

    /**
     * @desc 子商户信息修改
     */
    public function submerUpdate($user_id, $sub_mer_type = '', $sub_mer_name = '', $sub_mer_alias = '', $legal_name = '', $identity_id = '', $contacts_name = '', $mobile_id = '')
    {
        $_url = $this->base_url . 'merAccess/submer/update';
        $data = [
            'mer_id'    => $this->mer_id,
            'user_id'   => $user_id,
            'sub_mer_type'	=> $sub_mer_type,
            'sub_mer_name'	=> $sub_mer_name,
            'sub_mer_alias'	=> $sub_mer_alias,
            'legal_name'	=> Util::encrypt($legal_name),
            'identity_id'	=> Util::encrypt($identity_id),
            'contacts_name'	=> Util::encrypt($contacts_name),
            'mobile_id'	=> $mobile_id,
        ];
        return json_decode(Util::httpPost($data, $_url),1);
    }

    /**
     * @param $sub_mer_type String 子商户状态，1-开通 2-注销 3-暂停
     * @desc 子商户状态管理
     */
    public function submerUpdateState($shop_id, $sub_mer_type)
    {
        $_url = $this->base_url . 'merAccess/submer/updateState';
        $data = [
            'mer_id'        => $this->mer_id,
            'version'       => '1.0',
            'sub_mer_id'    => $shop_id,
            'sub_mer_state'	=> $sub_mer_type,
        ];
        return json_decode(Util::httpPost($data, $_url),1);
        
    }


    /**
     * @desc 绑定企业对公结算账户
     */
    public function enterprise($order_id, $user_id, $bank_account_name, $bank_account, $gate_id, $notify_url = '', $mobile_id = '', $bank_branch_name = '', $bank_branch_code = '')
    {
        $_url = $this->base_url . 'merAccess/bindcard/enterprise';
        $data = [
            'mer_id'	        => $this->mer_id,
            'version'	        => '1.0',
            'order_id'	        => $order_id,
            'mer_date'	        => date('Ymd'),
            'user_id'	        => $user_id,
            'bank_account_name'	=> Util::encrypt($bank_account_name),
            'bank_account'	    => Util::encrypt($bank_account),
            'gate_id'	        => $gate_id,
            'notify_url'	    => $notify_url,
            'mobile_id'	        => $mobile_id,
            'bank_branch_name'	=> $bank_branch_name,
            'bank_branch_code'	=> $bank_branch_code,
        ];
        return json_decode(Util::httpPost($data, $_url),1);
        
    }

    /**
     * @param $user_type string 子商户类型：1（个人商户），2 （个体工商户），3（企业商户）
     * @desc 绑定法人结算银行卡
     */
    public function bindcardOrder($order_id, $user_id, string $user_type, $card_id, $bank_account_name, $bank_mobile_id, $notify_url = '')
    {
        $_url = $this->base_url . 'merAccess/bindcard/order';
        $data = [
            'mer_id'	        => $this->mer_id,
            'version'	        => '1.1',
            'order_id'	        => $order_id,
            'mer_date'	        => date('Ymd'),
            'user_id'	        => $user_id,
            'user_type'	        => $user_type, // 子商户类型：1（个人商户），2 （个体工商户），3（企业商户）
            'card_id'	        => Util::encrypt($card_id),
            'bank_account_name'	=> Util::encrypt($bank_account_name),
            'bank_mobile_id'	=> $bank_mobile_id,
            'notify_url'	    => $notify_url,
        ];
        return json_decode(Util::httpPost($data, $_url),1);
    }

    /**
     * @desc 确认绑卡
     */
    public function bindcardConfirm($user_id, $trade_no, $verify_code)
    {
        $_url = $this->base_url . 'merAccess/bindcard/confirm';
        $data = [
            'mer_id'	    => $this->mer_id,
            'version'	    => '1.1',
            'trade_no'	    => $trade_no,
            'user_id'	    => $user_id,
            'verify_code'	=> $verify_code,
        ];
        return json_decode(Util::httpPost($data, $_url),1);
    }

    /**
     * @desc 子商户绑卡信息查询接口
     */
    public function bindCardInfo($user_id)
    {
        $_url = $this->base_url . 'merAccess/member/bindCardInfo';
        $data = [
            'mer_id'	=> $this->mer_id,
            'version'	=> '1.0',
            'user_id'	=> $user_id,
        ];
        return json_decode(Util::httpGet($data, $_url),1);
    }

    /**
     * @param  $user_type string 用户类型：1-个人；2-个体；3-企业
     * @desc 提现协议解绑
     */
    public function unBindCard($user_id, $order_id, $user_type, $p_agreement_id, $last_four_cardid)
    {
        $_url = $this->base_url . 'merAccess/bankcard/unBindCard';
        $data = [
            'mer_id'	=> $this->mer_id,
            'user_id'	=> $user_id,
            'order_id'	=> $order_id,
            'user_type'	=> $user_type, // 用户类型：1-个人；2-个体；3-企业
            'mer_date'	=> date('Ymd'),
            'p_agreement_id'	=> $p_agreement_id,
            'last_four_cardid'	=> $last_four_cardid,
        ];
        return json_decode(Util::httpPost($data, $_url),1);
    }

}